<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Ad extends Controller {

    public function action_list() {
        $pagination_arr = Paginationhelp::get_data('ad', 'id_ad');
        $ads_category = Adcategory::instances()->get_categories();
        $data = array(
            'result' => $pagination_arr['data'],
            'ads_category'=>$ads_category,
            'page_view' => $pagination_arr['pagination']
        );

        $view = Viewer::display('admin/modules/ad_list', $data);
        $this->response->body($view);
    }

    public function action_add() {
       Session::instance()->set('here', 'here');
        $ads_categories = Adcategory::instances()->get_categories();
        if ($_POST) {
            $ad = Ad::instances()->set($_POST);
            if ($ad) {
                Message::set('广告添加成功！');
                Request::current()->redirect(URL::base() . 'admin/ad/add');
            }
        }
        $data = array(
            'ads_categories'=>$ads_categories
        );
        
        $view = Viewer::display('admin/modules/ad_add',$data);
        $this->response->body($view);
    }

    public function action_edit() {
      Session::instance()->set('here', 'here');
        $id_ad = $this->request->param('id');
        $ads = Ad::instances($id_ad)->get();
        $ads_categories = Adcategory::instances()->get_categories();
        if ($_POST) {
           $ad = Ad::instances($id_ad)->update($_POST);
            if ($ad) {
                Message::set('广告修改成功！');
                Request::current()->redirect(URL::base() . 'admin/ad/edit/'.$id_ad);
            }
        }
        $data = array(
            'ads_categories'=>$ads_categories,
            'data'=>$ads,
            'current_id'=>$ads['id_category']
        );
        
        $view = Viewer::display('admin/modules/ad_edit',$data);
        $this->response->body($view);
    }

    public function action_delete() {
        $id_ad = $this->request->param('id');
          $flag =Ad::instances($id_ad)->delete();
        if ($flag) {
            Message::set('广告删除成功');
            Request::current()->redirect(URL::base() . 'admin/ad/list');
        } else {
            Message::set('广告删除失败', 'error');
            Request::current()->redirect(URL::base() . 'admin/ad/list');
        }
    }

}